/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.tabpane;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

/**
 * Heading Panel for a TabPanel, supports an icon, a text and a close button
 * 
 * @author Pascal
 */
public class HeaderPanel extends JPanel implements ActionListener {
    
    private JTabbedPane tabpane;
    
    /**
     * Initializes the HeaderPanel with an icon
     * 
     * @param tabpane the tabpane, the HeaderPanel belongs to
     * @param icon the icon to set to the HeaderPanel
     */
    public HeaderPanel(final JTabbedPane tabpane, Icon icon, boolean closable) {
        super(new BorderLayout(5, 0));
        
        if (tabpane == null) {
            throw new NullPointerException();
        }
        
        this.tabpane = tabpane;
        
        initComponents(tabpane, icon, closable);
    }
    
    /**
     * Initializes the HeaderPanel without an icon
     * 
     * @param tabpane the tabpane, the HeaderPanel belongs to
     */
    public HeaderPanel(final JTabbedPane tabpane, Icon icon) {
        this(tabpane, icon, true);
    }
    
    /**
     * Initializes the HeaderPanel without an icon
     * 
     * @param tabpane the tabpane, the HeaderPanel belongs to
     */
    public HeaderPanel(final JTabbedPane tabpane) {
        this(tabpane, null, true);
    }
    
    private void initComponents(final JTabbedPane tabpane, Icon icon, boolean closable) {        
        
        setOpaque(false);
        
        if (icon != null) {
            JLabel iconLabel = new JLabel(icon);
            
            add(iconLabel, BorderLayout.WEST);
        }
        
        JLabel label = new JLabel() {
            @Override
            public String getText() {
                //let the tabpane return the text
                int i = tabpane.indexOfTabComponent(HeaderPanel.this);
                if (i != -1) {
                    return tabpane.getTitleAt(i);
                }
                return null;
            }
        };
        
        add(label, BorderLayout.CENTER);
        
        if (closable) {
            TabCloseButton closeButton = new TabCloseButton();
            closeButton.addActionListener(this);

            add(closeButton, BorderLayout.EAST);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int i = tabpane.indexOfTabComponent(this);
        
        if (i != -1) {
            tabpane.remove(i);
        }
    }
}
